#ifndef _THREAD_H_
#define _THREAD_H_
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <functional>
#include <pthread.h>
using namespace std;
namespace ThreadModlue
{
    static u_int32_t num = 1;
    template <class T>
    class Thread
    {
        using func_t = function<void(T)>;

    private:
       void  EnableDetach()
        {
            cout << "线程被分离了：" << endl;
            _isdetach = true;
        }
       void  EnableRunning()
        {
            _isrunning = true;
        }
        static void *Runtine(void *arg)
        {
            Thread<T> *self = static_cast<Thread<T> *> (arg );
            self->EnableRunning();
            if (self->_isdetach)
                self->Detach();
            self->_func(self->_data);
            return nullptr;
        }

    public:
        Thread(func_t func, T data)
            : _func(func),
              _data(data),
              _isdetach(false),
              _isrunning(false),
              res(nullptr),
              _tid(0)
        {
            _name = "Thread" + to_string(num++);
        }
        void Detach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }
        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Runtine, this);
            if (n != 0)
            {
                cerr << "create thread fail:" << strerror(n) << endl;
                return false;
            }
            else
            {
                cout << _name << "create success" << endl;
                return true;
            }
        }
        bool stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    cerr << "cancel fail" << strerror(n) << endl;
                    return false;
                }
                else
                {
                    _isrunning = false;
                    cout << "stop sucess" << endl;
                    return true;
                }
            }
            return false;
        }
        void Join()
        {
            if (_isdetach)
            {
                cout << "你的线程已经分离，不能Join" << endl;
                return;
            }
            int n = pthread_join(_tid, &res);
            if (n != 0)
            {
                cerr << "join fail" << strerror(n) << endl;
            }
            else
            {
                cout << _name << "join success" << endl;
            }
        }
        ~Thread() = default;

    private:
        pthread_t _tid;
        string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
        T _data;
    };
}
#endif